package com.nbjtjc.safe.service.emg;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nbjtjc.safe.bean.Page;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.emg.EmgGoodsMapper;
import com.nbjtjc.safe.model.emg.EmgGoods;
import com.nbjtjc.safe.model.sys.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmgGoodsService {
    @Autowired
    private EmgGoodsMapper emgGoodsMapper;

    @CacheEvict(value="emgGoods", allEntries=true)
    public Result add(EmgGoods emgGoods) {
        Result result = new Result();
        if (ObjectUtil.isNull(emgGoods)) {
            return result;
        }
        if (ObjectUtil.isNotNull(emgGoods.getId()) && emgGoods.getId() != 0) {
            emgGoodsMapper.updateByPrimaryKeySelective(emgGoods);
        } else {
            if (ObjectUtil.isNull(emgGoods.getWarehouseId()) || ObjectUtil.isNull(emgGoods.getGoodsName())) {
                result.setFalse("关键字段不能为空");
                return result;
            }
            if (!checkValid(emgGoods.getWarehouseId(), emgGoods.getGoodsName())) {
                result.setFalse("该仓库已经存在该类型的物资");
                return result;
            }
            Subject subject = SecurityUtils.getSubject();
            SysUser sysUser = (SysUser) subject.getSession().getAttribute("user");
            emgGoods.setDeptId(sysUser.getDeptId().intValue());
            emgGoodsMapper.insert(emgGoods);
        }
        result.setData(emgGoods);
        return result;
    }

    @Cacheable(value = "emgGoods")
    public List<EmgGoods> countByCategory(){
        List<EmgGoods> emgGoodsList=emgGoodsMapper.countByCategory();
        if(CollectionUtil.isNotEmpty(emgGoodsList)){
            emgGoodsList.forEach(emgGoods->{
                EmgGoods temp=new EmgGoods();
                temp.setGoodsName(emgGoods.getGoodsName());
                List<EmgGoods> goodsDetail=emgGoodsMapper.search(temp, new Page());
                if(CollectionUtil.isNotEmpty(goodsDetail)){
                    emgGoods.getEmgGoodsList().addAll(goodsDetail);
                }
            });
        }

        return emgGoodsList;
    }
    private boolean checkValid(int warehouseId, String goodsName) {
        EmgGoods emgGoods = new EmgGoods();
        emgGoods.setWarehouseId(warehouseId);
        emgGoods.setGoodsName(goodsName);
        List<EmgGoods> emgGoodsList = emgGoodsMapper.select(emgGoods);
        if (CollectionUtil.isNotEmpty(emgGoodsList)) {
            return false;
        }
        return true;
    }
}
